package com.muyu.marketing.bargain.controller;

import com.muyu.common.core.domain.Result;
import com.muyu.common.core.web.controller.BaseController;
import com.muyu.common.core.web.page.DataPageResp;
import com.muyu.common.log.annotation.Log;
import com.muyu.common.log.enums.BusinessType;
import com.muyu.common.security.annotation.RequiresPermissions;
import com.muyu.marketing.bargain.domain.BargainRecord;
import com.muyu.marketing.bargain.domain.req.BargainRecordReq;
import com.muyu.marketing.bargain.service.BargainRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 砍价记录Controller
 * 
 * @author muyu
 * @date 2025-01-27
 */
@Slf4j
@RestController
@RequestMapping("/marketing/bargain/record")
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS})
@Tag(name = "砍价记录管理", description = "砍价记录相关接口")
public class BargainRecordController extends BaseController {
    
    @Autowired
    private BargainRecordService bargainRecordService;
    
    /**
     * 查询砍价记录列表
     */
    @GetMapping("/list")
    @Operation(summary = "查询砍价记录列表", description = "分页查询砍价记录列表")
    public Result<DataPageResp<BargainRecord>> list(BargainRecord bargainRecord) {
        try {
            List<BargainRecord> list = bargainRecordService.selectBargainRecordList(bargainRecord);
            return Result.success(new DataPageResp<>(0, list));
        } catch (Exception e) {
            log.error("查询砍价记录列表失败", e);
            return Result.error("查询砍价记录列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 导出砍价记录列表
     */
    @PostMapping("/export")
    @Operation(summary = "导出砍价记录列表", description = "导出砍价记录列表到Excel")
    @RequiresPermissions("marketing:bargain:export")
    @Log(title = "砍价记录", businessType = BusinessType.EXPORT)
    public void export(BargainRecord bargainRecord) {
        List<BargainRecord> list = bargainRecordService.selectBargainRecordList(bargainRecord);
        // TODO: 实现Excel导出功能
        // ExcelUtil.exportExcel(response, list, "砍价记录数据");
    }
    
    /**
     * 获取砍价记录详细信息
     */
    @GetMapping(value = "/{id}")
    @Operation(summary = "获取砍价记录详细信息", description = "根据ID获取砍价记录详细信息")
    public Result<BargainRecord> getInfo(@Parameter(description = "砍价记录ID", required = true) @PathVariable("id") Long id) {
        try {
            BargainRecord bargainRecord = bargainRecordService.selectBargainRecordById(id);
            return success(bargainRecord);
        } catch (Exception e) {
            log.error("获取砍价记录详细信息失败", e);
            return Result.error("获取砍价记录详细信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 新增砍价记录
     */
    @PostMapping
    @Operation(summary = "新增砍价记录", description = "创建新的砍价记录")
    @RequiresPermissions("marketing:bargain:add")
    @Log(title = "砍价记录", businessType = BusinessType.INSERT)
    public Result<Void> add(@Parameter(description = "砍价记录信息", required = true) @RequestBody @Validated BargainRecordReq bargainRecordReq) {
        try {
            int result = bargainRecordService.insertBargainRecord(bargainRecordReq);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("新增砍价记录失败");
            }
        } catch (Exception e) {
            log.error("新增砍价记录失败", e);
            return Result.error("新增砍价记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改砍价记录
     */
    @PutMapping
    @Operation(summary = "修改砍价记录", description = "更新砍价记录信息")
    @RequiresPermissions("marketing:bargain:edit")
    @Log(title = "砍价记录", businessType = BusinessType.UPDATE)
    public Result<Void> edit(@Parameter(description = "砍价记录信息", required = true) @RequestBody @Validated BargainRecord bargainRecord) {
        try {
            int result = bargainRecordService.updateBargainRecord(bargainRecord);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("修改砍价记录失败");
            }
        } catch (Exception e) {
            log.error("修改砍价记录失败", e);
            return Result.error("修改砍价记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除砍价记录
     */
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除砍价记录", description = "批量删除砍价记录")
    @RequiresPermissions("marketing:bargain:remove")
    @Log(title = "砍价记录", businessType = BusinessType.DELETE)
    public Result<Void> remove(@Parameter(description = "砍价记录ID数组", required = true) @PathVariable Long[] ids) {
        try {
            int result = bargainRecordService.deleteBargainRecordByIds(ids);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("删除砍价记录失败");
            }
        } catch (Exception e) {
            log.error("删除砍价记录失败", e);
            return Result.error("删除砍价记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 开始砍价
     */
    @PostMapping("/start")
    @Operation(summary = "开始砍价", description = "用户开始砍价")
    public Result<BargainRecord> startBargain(@Parameter(description = "用户ID", required = true) @RequestParam("userId") Long userId,
                                            @Parameter(description = "砍价商品ID", required = true) @RequestParam("bargainProductId") Long bargainProductId) {
        try {
            BargainRecord bargainRecord = bargainRecordService.startBargain(userId, bargainProductId);
            return Result.success(bargainRecord, "开始砍价成功");
        } catch (Exception e) {
            log.error("开始砍价失败", e);
            return Result.error("开始砍价失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行砍价
     */
    @PostMapping("/execute")
    @Operation(summary = "执行砍价", description = "用户执行砍价操作")
    public Result<BargainRecord> executeBargain(@Parameter(description = "用户ID", required = true) @RequestParam("userId") Long userId,
                                              @Parameter(description = "砍价商品ID", required = true) @RequestParam("bargainProductId") Long bargainProductId) {
        try {
            BargainRecord bargainRecord = bargainRecordService.executeBargain(userId, bargainProductId);
            return Result.success(bargainRecord, "砍价成功");
        } catch (Exception e) {
            log.error("执行砍价失败", e);
            return Result.error("执行砍价失败: " + e.getMessage());
        }
    }
    
    /**
     * 完成砍价
     */
    @PostMapping("/complete/{id}")
    @Operation(summary = "完成砍价", description = "完成砍价")
    @RequiresPermissions("marketing:bargain:edit")
    @Log(title = "砍价记录", businessType = BusinessType.UPDATE)
    public Result<Void> completeBargain(@Parameter(description = "砍价记录ID", required = true) @PathVariable("id") Long id) {
        try {
            int result = bargainRecordService.completeBargain(id);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("完成砍价失败");
            }
        } catch (Exception e) {
            log.error("完成砍价失败", e);
            return Result.error("完成砍价失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消砍价
     */
    @PostMapping("/cancel/{id}")
    @Operation(summary = "取消砍价", description = "取消砍价")
    public Result<Void> cancelBargain(@Parameter(description = "砍价记录ID", required = true) @PathVariable("id") Long id) {
        try {
            int result = bargainRecordService.cancelBargain(id);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("取消砍价失败");
            }
        } catch (Exception e) {
            log.error("取消砍价失败", e);
            return Result.error("取消砍价失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID查询砍价记录列表
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "根据用户ID查询砍价记录列表", description = "根据用户ID查询砍价记录列表")
    public Result<List<BargainRecord>> getListByUserId(@Parameter(description = "用户ID", required = true) @PathVariable("userId") Long userId) {
        try {
            List<BargainRecord> list = bargainRecordService.selectBargainRecordListByUserId(userId);
            return Result.success(list);
        } catch (Exception e) {
            log.error("根据用户ID查询砍价记录列表失败", e);
            return Result.error("根据用户ID查询砍价记录列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据砍价商品ID查询砍价记录列表
     */
    @GetMapping("/product/{bargainProductId}")
    @Operation(summary = "根据砍价商品ID查询砍价记录列表", description = "根据砍价商品ID查询砍价记录列表")
    public Result<List<BargainRecord>> getListByProductId(@Parameter(description = "砍价商品ID", required = true) @PathVariable("bargainProductId") Long bargainProductId) {
        try {
            List<BargainRecord> list = bargainRecordService.selectBargainRecordListByProductId(bargainProductId);
            return Result.success(list);
        } catch (Exception e) {
            log.error("根据砍价商品ID查询砍价记录列表失败", e);
            return Result.error("根据砍价商品ID查询砍价记录列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 统计砍价商品的总砍价人数
     */
    @GetMapping("/count/bargainers/{bargainProductId}")
    @Operation(summary = "统计砍价商品的总砍价人数", description = "统计砍价商品的总砍价人数")
    public Result<Integer> countBargainers(@Parameter(description = "砍价商品ID", required = true) @PathVariable("bargainProductId") Long bargainProductId) {
        try {
            Integer count = bargainRecordService.countBargainersByProductId(bargainProductId);
            return success(count);
        } catch (Exception e) {
            log.error("统计砍价商品的总砍价人数失败", e);
            return Result.error("统计砍价商品的总砍价人数失败: " + e.getMessage());
        }
    }
    
    /**
     * 统计砍价商品的成功砍价数
     */
    @GetMapping("/count/successful/{bargainProductId}")
    @Operation(summary = "统计砍价商品的成功砍价数", description = "统计砍价商品的成功砍价数")
    public Result<Integer> countSuccessfulBargains(@Parameter(description = "砍价商品ID", required = true) @PathVariable("bargainProductId") Long bargainProductId) {
        try {
            Integer count = bargainRecordService.countSuccessfulBargainsByProductId(bargainProductId);
            return success(count);
        } catch (Exception e) {
            log.error("统计砍价商品的成功砍价数失败", e);
            return Result.error("统计砍价商品的成功砍价数失败: " + e.getMessage());
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    @Operation(summary = "健康检查", description = "检查砍价记录服务是否正常运行")
    public Result<String> health() {
        try {
            return success("砍价记录服务运行正常");
        } catch (Exception e) {
            log.error("健康检查失败", e);
            return Result.error("健康检查失败: " + e.getMessage());
        }
    }
}